package cn.tedu.order.service;


import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;

    @Override
    @GlobalTransactional
    @Transactional
    public void create(Order order) {
        //远程调用“全局唯一id发号器”，获取orderId
        String s =  easyIdClient.nextId("order_business");
        Long orderId= Long.valueOf(s);
       //临时随机生成一个ID；完成发号器后，这行代码要删除
//        Long orderId=Math.abs(new Random().nextLong());
        order.setId(orderId);
        orderMapper.create(order);
//        if(Math.random()<0.5){
//            throw new RuntimeException("模拟异常");
//        }
        //远程调用库存，减少商品库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //远程调用账户，扣减账户金额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
